/*
 * @Author: 
 * @Date: 2022-01-26 13:58:44
 * @LastEditors: lqj
 * @LastEditTime: 2022-02-10 14:48:44
 * @Description: 组件传值、拆分
 */
import React, { Component } from 'react';
import Header from './components/Header'
import Footer from './components/Footer'
import List from './components/List'
import { nanoid } from 'nanoid'
import './index.css'

export default class TodoList extends Component {
  state = {
    todoList: []
  }
  componentDidMount() {
    const arr = []
    for (let index = 0; index < 4; index++) {
      arr.push({ id: nanoid(), name: `item-${index + 1}`, isCheck: index % 2 !== 1 })
    }
    this.setState({
      todoList: arr
    })
  }

  handleValue = (data) => {
    const { todoList } = this.state
    this.setState({
      todoList: [{ id: nanoid(), name: data, isCheck: false }, ...todoList]
    })
  }

  changeTodo = (data, flag) => {
    const { todoList } = this.state
    const arr = todoList.map(it => {
      return { ...it, isCheck: it.id === data.id ? flag : it.isCheck}
    })
    this.setState({ todoList: arr })
  }

  delTodo = (id) => {
    const { todoList } = this.state
    const arr = todoList.filter(it => id !== it.id)
    this.setState({ todoList: arr })
  }

  handleChangeList = (flag) => {
    const { todoList } = this.state
    const arr = todoList.filter(it => !it.isCheck)
    this.setState({ todoList: arr })
  }

  changeAllList = (flag) => {
    const { todoList } = this.state
    this.setState({ todoList: todoList.map(it => ({ ...it, isCheck: flag })) })
  }
  // 子传父值，通过函数获取
  render() {
    return (
      <div className='todo-wrap' style={{ marginTop: '20px' }}>
        <Header getValue={this.handleValue} />
        <List todoList={this.state.todoList} setCheck={this.changeTodo} deleteItem={this.delTodo} />
        <Footer todoList={this.state.todoList} clearAll={this.handleChangeList} changeAllList={this.changeAllList} />
      </div>
    )
  }
}
